<template>
  <div class="detail-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar
      title="开单详情"
      left-text="返回"
      left-arrow
      @click-left="onClickLeft"
    />

    <!-- 详情内容 -->
    <div class="detail-content" v-if="!loading && orderDetail">
      <!-- 基本信息卡片 -->
      <div class="info-card">
        <div class="card-header">
          <van-icon name="orders-o" size="18" color="#1989fa" />
          <span class="card-title">基本信息</span>
        </div>
        <div class="info-list">
          <div class="info-item">
            <span class="label">开单编号</span>
            <span class="value">{{ orderDetail.applicationNumber }}</span>
          </div>
          <div class="info-item">
            <span class="label">开单时间</span>
            <span class="value">{{ formatDateTime(orderDetail.createTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">院区名称</span>
            <span class="value">{{ orderDetail.hospitalAreaName }}</span>
          </div>
          <div class="info-item">
            <span class="label">联系电话</span>
            <span class="value">{{ orderDetail.contactPhone }}</span>
          </div>
          <div class="info-item">
            <span class="label">订单状态</span>
            <span class="value" :class="getStatusClass(orderDetail.status)">
              {{ getStatusText(orderDetail.status) }}
            </span>
          </div>
          <div class="info-item" v-if="orderDetail.remarks">
            <span class="label">备注信息</span>
            <span class="value">{{ orderDetail.remarks }}</span>
          </div>
        </div>
      </div>

      <!-- 检查项目详情 -->
      <div class="projects-card">
        <div class="card-header">
          <van-icon name="medical-o" size="18" color="#1989fa" />
          <span class="card-title">检查项目详情</span>
        </div>
        <div class="projects-list">
          <div 
            v-for="(project, index) in orderDetail.items" 
            :key="project.id"
            class="project-item"
          >
            <div class="project-header">
              <div class="project-basic">
                <div class="project-name">{{ project.projectName }}</div>
                <div class="project-code" v-if="project.projectCode">
                  项目编码：{{ project.projectCode }}
                </div>
              </div>
              <div class="project-price">
                <span class="price-label">单价</span>
                <span class="price-value">¥{{ project.projectPrice }}</span>
              </div>
            </div>
            
            <div class="project-details">
              <!-- 项目描述 -->
              <div class="detail-section" v-if="project.projectDescription">
                <div class="section-title">
                  <van-icon name="info-o" size="14" />
                  <span>检查目的</span>
                </div>
                <div class="section-content">{{ project.projectDescription }}</div>
              </div>
              
              <!-- 检查前准备 -->
              <div class="detail-section" v-if="project.preparationInstructions">
                <div class="section-title">
                  <van-icon name="warning-o" size="14" color="#ff6b35" />
                  <span>检查前注意事项</span>
                </div>
                <div class="section-content preparation-content">
                  {{ project.preparationInstructions }}
                </div>
              </div>
              
              <!-- 预计时长 -->
              <div class="detail-section" v-if="project.estimatedDuration">
                <div class="section-title">
                  <van-icon name="clock-o" size="14" />
                  <span>预计时长</span>
                </div>
                <div class="section-content">{{ project.estimatedDuration }}分钟</div>
              </div>
              
              <!-- 数量和小计 -->
              <div class="quantity-section">
                <div class="quantity-info">
                  <span class="quantity-label">数量：</span>
                  <span class="quantity-value">{{ project.quantity }}</span>
                </div>
                <div class="subtotal-info">
                  <span class="subtotal-label">小计：</span>
                  <span class="subtotal-value">¥{{ project.subTotal }}</span>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 费用汇总 -->
      <div class="summary-card">
        <div class="card-header">
          <van-icon name="balance-o" size="18" color="#1989fa" />
          <span class="card-title">费用汇总</span>
        </div>
        <div class="summary-content">
          <div class="summary-row">
            <span class="summary-label">项目总数</span>
            <span class="summary-value">{{ orderDetail.items?.length || 0 }}项</span>
          </div>
          <div class="summary-row">
            <span class="summary-label">检查费用</span>
            <span class="summary-value">¥{{ orderDetail.totalAmount }}</span>
          </div>
          <div class="summary-row total-row">
            <span class="summary-label">合计金额</span>
            <span class="summary-value total-amount">¥{{ orderDetail.totalAmount }}</span>
          </div>
        </div>
      </div>

      <!-- 温馨提示 -->
      <div class="tips-card">
        <div class="card-header">
          <van-icon name="bulb-o" size="18" color="#fa8c16" />
          <span class="card-title">温馨提示</span>
        </div>
        <div class="tips-content">
          <div class="tip-item">
            <van-icon name="checked" size="14" color="#52c41a" />
            <span>请仔细阅读各项检查的注意事项，做好检查前的准备工作</span>
          </div>
          <div class="tip-item">
            <van-icon name="checked" size="14" color="#52c41a" />
            <span>如有疑问，请及时联系医院工作人员</span>
          </div>
          <div class="tip-item">
            <van-icon name="checked" size="14" color="#52c41a" />
            <span>请按时前往指定院区进行检查，避免影响检查结果</span>
          </div>
          <div class="tip-item" v-if="hasPreparationInstructions">
            <van-icon name="warning-o" size="14" color="#ff6b35" />
            <span>部分检查项目需要特殊准备，请务必按要求执行</span>
          </div>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <van-loading size="24px" vertical>加载详情中...</van-loading>
    </div>

    <!-- 错误状态 -->
    <div v-if="error" class="error-container">
      <van-empty 
        image="error" 
        description="加载失败，请重试"
      >
        <van-button 
          round 
          type="primary" 
          @click="loadOrderDetail"
        >
          重新加载
        </van-button>
      </van-empty>
    </div>

    <!-- 底部操作按钮 -->
    <div class="detail-footer" v-if="!loading && orderDetail">
      <van-button 
        v-if="orderDetail.status === OrderApplicationStatus.Submitted"
        type="primary" 
        size="large"
        @click="goToPayment"
        class="action-btn"
      >
        去支付
      </van-button>
      <van-button 
        v-else-if="orderDetail.status === OrderApplicationStatus.Completed"
        type="primary" 
        size="large"
        @click="viewReport"
        class="action-btn"
      >
        查看报告
      </van-button>
      <van-button 
        type="default" 
        size="large"
        @click="goBack"
        class="back-btn"
      >
        返回列表
      </van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { Toast } from 'vant'
import apiService, { 
  type OrderApplicationDetailDto, 
  OrderApplicationStatus 
} from '../api/index'

/**
 * 开单详情页面组件
 * 展示开单记录的详细信息，包括检查项目详情、注意事项等
 */

const router = useRouter()
const route = useRoute()
const loading = ref(true)
const error = ref(false)
const orderDetail = ref<OrderApplicationDetailDto | null>(null)

/**
 * 检查是否有准备说明
 */
const hasPreparationInstructions = computed(() => {
  return orderDetail.value?.items.some(item => item.preparationInstructions)
})

/**
 * 返回上一页
 */
const onClickLeft = () => {
  router.back()
}

/**
 * 返回列表页
 */
const goBack = () => {
  router.push('/order-history')
}

/**
 * 格式化日期时间
 * @param dateTime 日期时间字符串
 * @returns 格式化后的日期时间
 */
const formatDateTime = (dateTime: string): string => {
  const date = new Date(dateTime)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

/**
 * 获取状态文本
 * @param status 状态值
 * @returns 状态文本
 */
const getStatusText = (status: OrderApplicationStatus): string => {
  const statusMap = {
    [OrderApplicationStatus.Draft]: '草稿',
    [OrderApplicationStatus.Submitted]: '待支付',
    [OrderApplicationStatus.Paid]: '已支付',
    [OrderApplicationStatus.Progress]: '进行中',
    [OrderApplicationStatus.Completed]: '已完成',
    [OrderApplicationStatus.Cancelled]: '已取消'
  }
  return statusMap[status] || '未知状态'
}

/**
 * 获取状态样式类
 * @param status 状态值
 * @returns 样式类名
 */
const getStatusClass = (status: OrderApplicationStatus): string => {
  const classMap = {
    [OrderApplicationStatus.Draft]: 'status-draft',
    [OrderApplicationStatus.Submitted]: 'status-pending',
    [OrderApplicationStatus.Paid]: 'status-paid',
    [OrderApplicationStatus.Progress]: 'status-progress',
    [OrderApplicationStatus.Completed]: 'status-completed',
    [OrderApplicationStatus.Cancelled]: 'status-cancelled'
  }
  return classMap[status] || ''
}

/**
 * 加载开单详情
 */
const loadOrderDetail = async () => {
  try {
    loading.value = true
    error.value = false
    
    const orderId = Number(route.params.id)
    if (!orderId) {
      Toast('无效的订单ID')
      router.back()
      return
    }
    
    console.log('加载开单详情，ID:', orderId)
    
    const response = await apiService.getOrderApplicationDetail(orderId)
    
    if (response.code === 200 && response.data) {
      orderDetail.value = response.data
      console.log('开单详情加载成功:', response.data)
    } else {
      error.value = true
      Toast(response.message || '加载详情失败')
    }
  } catch (err) {
    console.error('加载开单详情失败:', err)
    error.value = true
    Toast('网络错误，请稍后重试')
  } finally {
    loading.value = false
  }
}

/**
 * 去支付
 */
const goToPayment = () => {
  if (!orderDetail.value) return
  
  // 构造支付页面需要的数据
  const paymentData = {
    orderId: orderDetail.value.id,
    orderNumber: orderDetail.value.applicationNumber,
    hospitalName: orderDetail.value.hospitalAreaName,
    userId: orderDetail.value.userId, // 添加用户ID
    items: orderDetail.value.items.map(item => ({
      id: item.id,
      name: item.projectName,
      description: item.projectDescription || '',
      price: item.projectPrice,
      quantity: item.quantity
    })),
    totalAmount: orderDetail.value.totalAmount
  }
  
  router.push({
    path: '/order-payment',
    query: {
      orderData: JSON.stringify(paymentData)
    }
  })
}

/**
 * 查看报告
 */
const viewReport = () => {
  Toast('报告查看功能开发中...')
}

/**
 * 页面挂载时加载数据
 */
onMounted(() => {
  console.log('开单详情页面已加载，路由参数:', route.params)
  loadOrderDetail()
})
</script>

<style scoped>
.detail-container {
  min-height: 100vh;
  background-color: #f7f8fa;
  padding-bottom: 80px;
}

.detail-content {
  padding: 16px;
}

/* 卡片通用样式 */
.info-card,
.projects-card,
.summary-card,
.tips-card {
  background: white;
  border-radius: 12px;
  margin-bottom: 12px;
  overflow: hidden;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
}

.card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  background: #fafafa;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
  color: #333;
}

/* 基本信息样式 */
.info-list {
  padding: 16px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-bottom: 1px solid #f5f5f5;
}

.info-item:last-child {
  border-bottom: none;
}

.info-item .label {
  font-size: 14px;
  color: #666;
  min-width: 80px;
}

.info-item .value {
  font-size: 14px;
  color: #333;
  text-align: right;
  flex: 1;
}

/* 状态样式 */
.status-draft {
  color: #666 !important;
}

.status-pending {
  color: #fa8c16 !important;
}

.status-paid {
  color: #52c41a !important;
}

.status-progress {
  color: #1890ff !important;
}

.status-completed {
  color: #0ea5e9 !important;
}

.status-cancelled {
  color: #ff4d4f !important;
}

/* 项目列表样式 */
.projects-list {
  padding: 16px;
}

.project-item {
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
}

.project-item:last-child {
  margin-bottom: 0;
}

.project-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
  background: #fafafa;
  border-bottom: 1px solid #f0f0f0;
}

.project-basic {
  flex: 1;
}

.project-name {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.project-code {
  font-size: 12px;
  color: #999;
}

.project-price {
  text-align: right;
}

.price-label {
  display: block;
  font-size: 12px;
  color: #666;
  margin-bottom: 2px;
}

.price-value {
  font-size: 18px;
  font-weight: 600;
  color: #ff6b35;
}

.project-details {
  padding: 16px;
}

.detail-section {
  margin-bottom: 16px;
}

.detail-section:last-child {
  margin-bottom: 0;
}

.section-title {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 8px;
}

.section-content {
  font-size: 14px;
  color: #666;
  line-height: 1.5;
  padding-left: 20px;
}

.preparation-content {
  background: #fff7e6;
  padding: 12px;
  border-radius: 6px;
  border-left: 3px solid #ff6b35;
  margin-left: 0;
  padding-left: 12px;
}

.quantity-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 0;
  border-top: 1px solid #f0f0f0;
  margin-top: 12px;
}

.quantity-info,
.subtotal-info {
  display: flex;
  align-items: center;
  gap: 4px;
}

.quantity-label,
.subtotal-label {
  font-size: 14px;
  color: #666;
}

.quantity-value {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.subtotal-value {
  font-size: 16px;
  color: #ff6b35;
  font-weight: 600;
}

/* 费用汇总样式 */
.summary-content {
  padding: 16px;
}

.summary-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 14px;
}

.summary-row.total-row {
  border-top: 1px solid #f0f0f0;
  margin-top: 8px;
  padding-top: 12px;
  font-weight: 600;
}

.summary-label {
  color: #666;
}

.summary-value {
  color: #333;
}

.total-amount {
  font-size: 18px;
  color: #ff6b35 !important;
  font-weight: 600;
}

/* 温馨提示样式 */
.tips-content {
  padding: 16px;
}

.tip-item {
  display: flex;
  align-items: flex-start;
  gap: 8px;
  margin-bottom: 12px;
  font-size: 14px;
  color: #666;
  line-height: 1.5;
}

.tip-item:last-child {
  margin-bottom: 0;
}

/* 加载和错误状态 */
.loading-container,
.error-container {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 60px 20px;
}

/* 底部操作按钮 */
.detail-footer {
  background: white;
  padding: 12px 16px;
  border-top: 1px solid #f0f0f0;
  display: flex;
  gap: 12px;
  margin-top: 12px;
}

.action-btn {
  flex: 2;
}

.back-btn {
  flex: 1;
}
</style>